<template>
    <div class="packageConfig">
        <el-button @click="addNewPackage">添加新套餐</el-button>
        <el-table :data="packageData" border style="width: 100%;margin-top:20px" v-loading="loadingPackage" ref="table" :height="tableHeight" :row-class-name="tableRowClassName">
            <el-table-column prop="packageName" label="产品套餐名称" align="center"></el-table-column>
            <el-table-column prop="remark" label="套餐说明" align="center"></el-table-column>
            <el-table-column prop="packagePrice" label="套餐价格" align="center"></el-table-column>
            <el-table-column label="有效期" align="center">
                <template slot-scope="scope">
                    {{momentTime(scope.row.validTime)}}-{{momentTime(scope.row.invalidTime)}}
                </template>
            </el-table-column>
            <el-table-column prop="discount" label="折扣" align="center"></el-table-column>
            <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                    <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑产品套餐</el-button>
                    <el-button size="mini" @click="hidepackage(scope.$index, scope.row)" v-show="new Date().getTime()/1000>scope.row.validTime&&new Date().getTime()/1000<scope.row.invalidTime">{{scope.row.isDisplayed==1?'隐藏':'显示'}}</el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-dialog :title="dialogText" :visible.sync="dialogVisible" :append-to-body="true" width="40%" :modal="false" :close-on-click-modal="false" @close="resetForm">
            <el-form :model="productform" label-width="140px" ref="productform" :rules="rules" v-loading="loadingDialog">
                <el-form-item label="产品套餐名称:" prop="packageName">
                    <el-input v-model.trim="productform.packageName"></el-input>
                </el-form-item>
                <el-form-item label="产品套餐卡:" prop="productContains">
                    <el-button class="dialog_confirm" type="primary" @click="addProduct">增加</el-button>
                </el-form-item>
                <el-table :data="cardData" style="width: 94%;margin:20px auto 20px 40px">
                    <el-table-column label="产品类型" align="center" width="320px">
                        <template slot-scope="scope">
                            <el-select v-model="productform.productContains[scope.$index].productId">
                                <el-option v-for='(pro,i) in cardData[scope.$index].product' :key="'pro'+i" :value="pro.id" :label="pro.productName"></el-option>
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column label="数量" align="center">
                        <template slot-scope="scope">
                            <el-input-number v-model="productform.productContains[scope.$index].num" :min="1"></el-input-number>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" align="center">
                        <template slot-scope="scope">
                            <el-button size="mini" type="danger" class="dialog_confirm" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-row>
                  <el-col :span="12">
                      <el-form-item label="生效开始时间:" prop="validTime">
                        <el-date-picker v-model="productform.validTime" type="date" placeholder="选择日期" format="yyyy 年 MM 月 dd 日" value-format="timestamp" :picker-options="pickerOptionsStart" @change="changeEnd"></el-date-picker>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                      <el-form-item label="生效结束时间:" prop="invalidTime">
                    <el-date-picker v-model="productform.invalidTime" type="date" placeholder="选择日期" format="yyyy 年 MM 月 dd 日" value-format="timestamp" :picker-options="pickerOptionsEnd" @change="changeStart"></el-date-picker>
                  </el-form-item>
                  </el-col>
                </el-row>
                <el-form-item label="套餐价格:" prop="packagePrice">
                    <el-input v-model.trim="productform.packagePrice"></el-input>
                </el-form-item>
                <el-form-item label="折扣:" prop="discount">
                    <el-input v-model.trim="productform.discount"></el-input>
                </el-form-item>
                <el-form-item label="套餐说明:" prop="remark">
                    <el-input type="textarea" v-model.trim="productform.remark"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button class="dialog_close" @click="dialogVisible = false;resetForm()" :disabled="btnDisable">取 消</el-button>
                <el-button class="dialog_confirm" type="primary" @click="submitAddPackage" v-show="btnAdd" :disabled="btnDisable">确 定</el-button>
                <el-button class="dialog_confirm" type="primary" @click="submitEditPackage" v-show="!btnAdd" :disabled="btnDisable">确 定</el-button>
            </div>
        </el-dialog>

        <div class="page_block">
            <el-pagination
                background
                @current-change="handleCurrentChange"
                :current-page.sync="currentPage"
                :page-size="11"
                small
                layout="prev, pager, next, jumper"
                :total="totalCount">
            </el-pagination>
        </div>
    </div>

</template>
<script>
import base from "../api/base.js";
import moment from "moment";
export default {
  data() {
    var validateAmount = (rule, value, callback) => {
      var reg1 = /^[0-9]+([.]{1}[0-9]{1,2}){0,1}$/;
      var reg2 = /^[0-9]+([.]{1}[0-9]+){0,1}$/;
      if(reg2.test(value)){
         this.productform.packagePrice=Number(this.productform.packagePrice).toString()
        if(value>0){
          if(reg1.test((Number(value).toString()))){
            callback();
          }else{
            callback(new Error("最小收款单位不能低于分"));
          }
        }else{
          callback(new Error('输入金额需要大于零'))
        }
      }else{
        callback(new Error('输入格式有误'))
      }
  }

  var validateDiscount= (rule, value, callback) => {
      var reg = /^[0-9.]+$/;
      if(reg.test(value)){
         this.productform.discount=Number(this.productform.discount).toString()
        callback()
      }else{
        callback(new Error('只能输入正整数或小数'))
      }
  }
    return {
      tableHeight:700,
      // 套餐卡table
      packageData: [],
      dialogVisible: false,
      dialogText: "添加产品套餐",
      pickerOptionsStart: {},
      pickerOptionsEnd:{},
      //   产品添加或编辑的表单数据
      productform: {
        token: localStorage.token,
        productPackageId: "",
        packageName: "",
        productContains: [],
        packagePrice: "",
        discount: "",
        validTime: "",
        invalidTime: "",
        remark: "",
      },
      rules: {
        packageName: [
          { required: true, message: "请填写套餐名称", trigger: "blur" }
        ],
        productContains: [
          { required: true, message: "请选择产品卡", trigger: "blur" }
        ],
        packagePrice: [
          { required: true, message: "请填写套餐价格", trigger: "blur" },
          { validator: validateAmount, trigger: 'blur' }
        ],
        validTime: [
          { required: true, message: "请选择日期", trigger: "blur" }
        ],
        invalidTime: [
          { required: true, message: "请选择日期", trigger: "blur" }
        ],
        discount: [
          { required: true, message: "请填写套餐折扣", trigger: "blur" },
          { validator: validateDiscount, trigger: 'blur' }
        ],
        remark: [{ required: true, message: "请填写套餐说明", trigger: "blur" }]
      },
      //   产品卡table
      cardData: [],
      //   产品卡总类别
      productCard: [],
      loadingPackage: true,
      loadingDialog: false,
      btnDisable:false,
      btnAdd: true,
      currentPage:1,
      totalCount:0,
      pageSize:11,
    };
  },
  methods: {
    changeStart (){
        this.pickerOptionsStart = Object.assign({},this.pickerOptionsStart,{
          disabledDate: (time) => {
            return time.getTime() > this.productform.invalidTime
          }
        })
      },
      changeEnd (){
        this.pickerOptionsEnd = Object.assign({},this.pickerOptionsEnd,{
          disabledDate: (time) => {
            return time.getTime() < this.productform.validTime
            }
        })
      },
    //   编辑套餐
    handleEdit(index, row) {
      var length = row.productPackageContent.length;
      this.btnAdd = false;
      this.productform.productContains = [];
      this.cardData = [];
      this.dialogText = "编辑产品套餐";
      this.dialogVisible = true;
      this.productform.packageName = row.packageName;
      this.productform.packagePrice = row.packagePrice;
      this.productform.discount = row.discount;
      this.productform.validTime=row.validTime*1000
      this.productform.invalidTime=row.invalidTime*1000
      this.productform.remark = row.remark;
      this.productform.productPackageId = row.id;
      for (var i = 0; i < length; i++) {
        this.productform.productContains.push({ productId: "", num: 1 });
        this.productform.productContains[i].productId =
          row.productPackageContent[i].product.id;
        this.productform.productContains[i].num =
          row.productPackageContent[i].num;
        this.cardData.push({ product: {} });
        this.cardData[i].product = this.productCard;
      }
    },

    // 添加产品卡
    addProduct() {
      this.cardData.push({ product: {} });
      this.cardData[this.cardData.length - 1].product = this.productCard;
      this.productform.productContains.push({ productId: "", num: 1 });
    },
    // 删除产品卡
    handleDelete(index, row) {
      this.$confirm("是否确定删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.cardData.splice(index, 1);
        this.productform.productContains.splice(index, 1);
      });
    },
    // 添加新的产品套餐
    addNewPackage() {
      this.resetForm();
      this.btnAdd = true;
      this.dialogText = "添加产品套餐";
      this.dialogVisible = true;
    },
    // 隐藏或显示套餐的状态
    hidepackage(index, row) {
      this.$confirm("是否确定更改套餐状态?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      }).then(() => {
        this.loadingPackage = true;
        let displayStatus=row.isDisplayed==1?2:1
        this.$axios({
                url: base.baseUrl2 + "/v1/agent/agent-package/update",
                method: "POST",
                header: { "content-type": "application/x-www-form-urlencoded" },
                data: {
                  token:localStorage.token,
                  productPackageId:row.id,
                  isDisplayed:displayStatus,
                },
                transformRequest: [
                  function(data) {
                    let ret = "";
                    for (let it in data) {
                      ret +=
                        encodeURIComponent(it) +
                        "=" +
                        encodeURIComponent(data[it]) +
                        "&";
                    }
                    return ret;
                  }
                ]
              }).then(res => {
                 this.loadingPackage = false;
                if (res.data.status == 4000) {
                  this.alertTip(res.data.message);
                } else if (res.data.status == 2000) {
                  this.alertTip("编辑成功");
                  this.getAgentPackageList();
                } else if (res.data.status == 2001) {
                  this.$router.push("/login");
                }
              }).catch(error=>{
                this.loadingPackage = false;
                console.log(error)
                this.alertTip("网络异常收银失败，请检查网络稍后再试")
                });
      });
    },
    // 提交编辑套餐数据
    submitEditPackage() {
      this.$refs.productform.validate(valid => {
        if (valid) {
          this.productform.productContains.forEach(el => {
            if (el.num == 0 || el.productId == "") {
              this.alertTip("产品卡不能为空或数量不能为0");
              return false;
            }
            this.$confirm("是否确定修改?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消"
            }).then(() => {
              this.loadingDialog=true
              this.btnDisable=true
              var submitData={}
              submitData.productPackageId=this.productform.productPackageId
              submitData.packageName=this.productform.packageName
              submitData.packagePrice=this.productform.packagePrice
              submitData.discount=this.productform.discount
              submitData.remark=this.productform.remark
              submitData.productContains=[]
              submitData.validTime=parseInt(this.productform.validTime/1000)
              submitData.invalidTime=parseInt((this.productform.invalidTime+86399000)/1000)
              this.productform.productContains.forEach((el, index) => {
                submitData.productContains[index] = el;
              });
              submitData.token=localStorage.token;
              submitData.productContains = JSON.stringify(
                submitData.productContains
              );
              this.$axios({
                url: base.baseUrl2 + "/v1/agent/agent-package/update",
                method: "POST",
                header: { "content-type": "application/x-www-form-urlencoded" },
                data: submitData,
                transformRequest: [
                  function(data) {
                    let ret = "";
                    for (let it in data) {
                      ret +=
                        encodeURIComponent(it) +
                        "=" +
                        encodeURIComponent(data[it]) +
                        "&";
                    }
                    return ret;
                  }
                ]
              }).then(res => {
                this.loadingDialog=false
                this.btnDisable=false
                if (res.data.status == 4000) {
                  this.alertTip(res.data.message);
                } else if (res.data.status == 2000) {
                  this.alertTip("编辑成功");
                  this.dialogVisible = false;
                  this.getAgentPackageList();
                } else if (res.data.status == 2001) {
                  this.$router.push("/login");
                }
              }).catch(error=>{
                this.loadingDialog=false
                this.btnDisable=false
                console.log(error)
                this.alertTip("网络异常收银失败，请检查网络稍后再试")
                });
            });
          });
        } else {
          this.alertTip("选项有误,不能提交!");
        }
      });
    },
    // 提交添加套餐数据
    submitAddPackage() {
      this.$refs.productform.validate(valid => {
        if (valid) {
          this.productform.productContains.forEach(el => {
            if ( el.productId == "") {
              this.alertTip("产品卡不能为空或数量不能为0");
              return false;
            }
            this.$confirm("是否确定添加?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消"
            }).then(() => {
              this.loadingDialog=true
              this.btnDisable=true
              var submitData={}
              submitData.packageName=this.productform.packageName
              submitData.packagePrice=this.productform.packagePrice
              submitData.discount=this.productform.discount
              submitData.remark=this.productform.remark
              submitData.productContains=[]
              submitData.validTime=parseInt(this.productform.validTime/1000)
              submitData.invalidTime=parseInt((this.productform.invalidTime+86399000)/1000)
              this.productform.productContains.forEach((el, index) => {
                submitData.productContains[index] = el;
              });
              submitData.token=localStorage.token;
              submitData.productContains = JSON.stringify(
                submitData.productContains
              );
              this.$axios({
                url: base.baseUrl2 + "/v1/agent/agent-package/create",
                method: "POST",
                header: { "content-type": "application/x-www-form-urlencoded" },
                data: submitData,
                transformRequest: [
                  function(data) {
                    let ret = "";
                    for (let it in data) {
                      ret +=
                        encodeURIComponent(it) +
                        "=" +
                        encodeURIComponent(data[it]) +
                        "&";
                    }
                    return ret;
                  }
                ]
              }).then(res => {
                this.loadingDialog=false
                this.btnDisable=false
                if (res.data.status == 4000) {
                  this.alertTip(res.data.message);
                } else if (res.data.status == 2000) {
                  this.alertTip("添加成功");
                  this.dialogVisible = false;
                  this.getAgentPackageList();
                } else if (res.data.status == 2001) {
                  this.$router.push("/login");
                }
              }).catch(error=>{
                this.loadingDialog=false
                this.btnDisable=false
                console.log(error)
                this.alertTip("网络异常收银失败，请检查网络稍后再试")
              });
            });
          });
        }else {
          this.alertTip("选项有误,不能提交!");
        }
      });
    },
    // 获取代理商设置的套餐列表
    getAgentPackageList(val=0) {
      this.$axios({
        url: base.baseUrl2 + "/v1/agent/agent-package/list",
        method: "POST",
        header: { "content-type": "application/x-www-form-urlencoded" },
        data: {
          token: localStorage.token,
          // token: "9f063cd31dd559824941e3d47fc69abc#100230",
          pageIndex:val,
          pageSize:this.pageSize,
        },
        transformRequest: [
          function(data) {
            let ret = "";
            for (let it in data) {
              ret +=
                encodeURIComponent(it) +
                "=" +
                encodeURIComponent(data[it]) +
                "&";
            }
            return ret;
          }
        ]
      }).then(res => {
        this.loadingPackage = false;
        if (res.data.status == 4000) {
          this.alertTip(res.data.message);
        } else if (res.data.status == 2000) {
          this.packageData = res.data.data.productPackage;
          this.totalCount=Number(res.data.page.totalRows)
        } else if (res.data.status == 2001) {
          this.$router.push("/login");
        }
      }).catch(error=>{
        console.log(error)
        this.alertTip("网络异常收银失败，请检查网络稍后再试")
      });
    },

    // 获取代理商设置的产品卡列表
    getAgentProductList() {
      this.$axios({
        url: base.baseUrl2 + "/v1/agent/agent-package/product-list",
        method: "POST",
        header: { "content-type": "application/x-www-form-urlencoded" },
        data: {
          token: localStorage.token,
          // token: "9f063cd31dd559824941e3d47fc69abc#100230"
        },
        transformRequest: [
          function(data) {
            let ret = "";
            for (let it in data) {
              ret +=
                encodeURIComponent(it) +
                "=" +
                encodeURIComponent(data[it]) +
                "&";
            }
            return ret;
          }
        ]
      }).then(res => {
        if (res.data.status == 4000) {
          this.alertTip(res.data.message);
        } else if (res.data.status == 2000) {
          this.productCard = res.data.data.product;
          // this.cardData.push(res.data.data)
        } else if (res.data.status == 2001) {
          this.$router.push("/login");
        }
      }).catch(error=>{
        console.log(error)
        this.alertTip("网络异常收银失败，请检查网络稍后再试")
      });
    },
    // 格式化时间
    momentTime(time) {
      return moment(time * 1000).format("YYYY/MM/DD");
    },
    // 重置表单数据
    resetForm() {
      if (this.$refs.productform !== undefined) {
        this.$refs.productform.resetFields();
      }
      this.productform.packageName = "";
      this.productform.productContains = [{ productId: "", num: 1 }];
      this.productform.packagePrice = "";
      this.productform.discount = "";
      this.productform.remark = "";
      this.cardData = [{ prosduct: {} }];
      this.cardData[0].product = this.productCard;
      //   this.dialogVisible=false
    },
    // 套餐列表的状态变化样式
    tableRowClassName({row, rowIndex}) {
        if (row.isDisplayed === 2) {
          return 'hide-row';
        } 
        return '';
      },
      // 分页点击事件
    handleCurrentChange(val){
      this.getAgentPackageList(val-1);
    },
    //   提示框
    alertTip(msg) {
      this.$alert(msg, "提示", {
        confirmButtonText: "确定"
      });
    }
  },
  created() {
    this.getAgentPackageList();
    this.getAgentProductList();
  },
  updated(){
    if(this.$refs.table.$el.getElementsByTagName('tr').length>1){
      const trHeaderHeight=this.$refs.table.$el.getElementsByTagName('tr')[0].offsetHeight
      const trBodyHeight=this.$refs.table.$el.getElementsByTagName('tr')[1].offsetHeight
      const trNum=parseInt((window.innerHeight-300-trHeaderHeight)/trBodyHeight)
      this.tableHeight=trHeaderHeight+trBodyHeight*trNum+1
    } 
  },
};
</script>
<style>
.el-table .hide-row {
    background: #f5f7fa;
  }
</style>

<style scoped>
.el-table .warning-row {
    background: red;
  }
.packageConfig {
  margin: 20px 40px auto 40px;
}
.page_block{
    position: absolute;
    margin-top:12px;
    right: 5%;
}
</style>



